// 引入之前创建的实例文件
import axios from "./request";

//定义一个二维数组存放逻辑避免函数内部大量判断,优化逻辑

const dataList=[
[(fileName)=> fileName.indexOf('pdf') !== -1 || fileName.indexOf('PDF') !== -1,(data)=> new Blob([data], { type: "application/pdf" })],
[(fileName)=> fileName.indexOf('docx') !== -1 || fileName.indexOf('DOCX') !== -1,(data)=> new Blob([data], { type: "application/docx" })],
[(fileName)=> fileName.indexOf('zip') !== -1 || fileName.indexOf('ZIP') !== -1,(data)=> new Blob([data], { type: "application/zip" })],
[(fileName)=> fileName.indexOf('JPG') !== -1 || fileName.indexOf('jpg') !== -1,(data)=> new Blob([data], { type: "application/jpg" })],
[(fileName)=> fileName.indexOf('xlsx') !== -1 || fileName.indexOf('XLSX') !== -1,(data)=> new Blob([data], { type: "application/xlsx" })],
[(fileName)=> fileName.indexOf('xmind') !== -1 || fileName.indexOf('xmind') !== -1,(data)=> new Blob([data], { type: "application/xmind" })]
]
const httpReques= {

  // 默认form请求
  defaultHttpForm4Excel: function (url, data, callback, error) {
    axios({
      url: url,
      data: data,
      method: "post",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
    })
      .then((res) => {
        if (callback) callback(res);
      })
      .catch((err) => {
        if (error) error(err);
      });
  },


  //文件下载处理的
  defaultDownloadPost: function (url, type,params, fileName, callback, error) {
    axios({
      url: url,// 请求地址
      data: params, // 参数
      method: type, // 方式
      timeout: 1000 * 60 * 60, //改为1小时超时
      responseType: "blob", //设置返回数据类型,前后端保持一致
    })
      .then((res) => {
        let data = res.data;
        fileName ? fileName : (fileName = "currentFile");
        if (!data) {
          return;
        }
        let blob;
        // 知道到符合条件的
        let  currentFileType = dataList.find(item=> item[0](fileName))
         if(currentFileType){
        // 进行保存数据
      blob=currentFileType[1](data)
      }else{
        // 没有符合条件时的执行的逻辑

       }
        let url = window.URL.createObjectURL(blob);
         // 只有chrome 和Firefox (内核) 支持
        if ("download" in document.createElement("a")) {
          const a = document.createElement("a");
          a.href = url;
          a.download = fileName;
          a.style.display = "none";
        // dom操作
          document.body.appendChild(a);
          a.click();
        // 释放 Blob对象
          URL.revokeObjectURL(a.href);
        // dom操作
          document.body.removeChild(a);
        } else {
        //其他浏览器
          navigator.msSaveBlob(blob);
        }
        if (callback) callback(res);
      })
      .catch((err) => {
        if (error) error(err);
      });
  },
};

export default httpReques;
